//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package impl

import (
	"bytes"
	"strings"

	"atomgit.com/openlinksaas-org/search-proxy/core"
	"github.com/antchfx/htmlquery"
)

type NugetParser struct{}

func (parser *NugetParser) MatchUrl(url string) bool {
	return strings.HasPrefix(url, "https://www.nuget.org/packages")
}

func (parser *NugetParser) Parse(url string) ([]*core.SearchEntry, error) {
	body, err := GetPage(url)
	if err != nil {
		return nil, err
	}

	doc, err := htmlquery.Parse(bytes.NewBuffer(body))
	if err != nil {
		return nil, err
	}

	retList := []*core.SearchEntry{}
	liElList := htmlquery.Find(doc, "//ul[@class='list-packages']/li[@class='package']")
	for _, liEl := range liElList {
		linkEl := htmlquery.FindOne(liEl, "//div[@class='package-header']/a[@class='package-title']")
		if linkEl != nil {
			retList = append(retList, &core.SearchEntry{
				Title:   htmlquery.InnerText(linkEl),
				Url:     "https://www.nuget.org" + htmlquery.SelectAttr(linkEl, "href"),
				Summary: htmlquery.InnerText(liEl),
			})
		}
	}
	return retList, nil
}
